
from feature import Feature, FeatureParser, registerFeatureParserClass
from wigglefeature import WiggleFeatureParser

def _parseCounts(genomic, st):
    if not "/" in st:
        cts = {'A':0, 'C':0, 'G':0, 'T':0}
        cts[genomic] = int(st)
    else:
        cts = {}
        (cts['A'], cts['C'], cts['G'], cts['T']) = tuple(map(int, st.split("/")))
    return cts

class ReadsPerBaseCountFeature(Feature):

    def getDetails(self):
        cols = self.content.strip().split("\t")
        self.genomic = cols[0]
        self.reads = int(cols[1])
        self.weightedReads = float(cols[2])
        self.fragments = int(cols[3])
        self.snp = (cols[4]=="T")
        self.hqReads = _parseCounts(self.genomic, cols[5])
        self.hqFragments = _parseCounts(self.genomic, cols[6])
        self.hqSnp = self.snp and (self.hqFragments[self.genomic] != sum([ct for (base, ct) in self.hqFragments.items()]))
        return self

    def getFragmentCounts(self):
        return tuple([self.hqFragments[base] for base in ['A', 'C', 'G', 'T']])

class ReadsPerBaseCountFeatureParser(WiggleFeatureParser):

    def parse(self, line):
        feature = WiggleFeatureParser.parse(self, line)
        if feature == None: return None
        return ReadsPerBaseCountFeature(feature.chr, feature.spos, feature.epos, feature.content)

registerFeatureParserClass("coverage_summary", ReadsPerBaseCountFeatureParser)
